<template>
  <div class="page-container">
    <!-- Main Content -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 快捷金额配置 -->
        <el-col :span="16">
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex; align-items: center; justify-content: space-between;">
                <span style="font-size: 16px; font-weight: 600;">Quick Amount Settings</span>
                <el-tag type="info">
                  Total {{ currentAmounts.length }} amount options
                </el-tag>
              </div>
            </template>

            <div style="margin-bottom: 20px;">
              <el-alert
                title="Configuration Guide"
                type="info"
                description="Configure quick amount options displayed on the user recharge page. Users can click these amounts to quickly fill in the recharge amount. Amounts will be automatically deduplicated and sorted in ascending order."
                show-icon
                :closable="false"
                style="margin-bottom: 20px;"
              />
            </div>

            <!-- 当前快捷金额列表 -->
            <div class="amounts-list">
              <h4>Current Quick Amounts:</h4>
              <div class="amount-tags">
                <el-tag
                  v-for="(amount, index) in currentAmounts"
                  :key="`current-${index}`"
                  size="large"
                  closable
                  @close="removeAmount(index)"
                  style="margin: 4px 8px 4px 0;"
                >
                  {{ amount }}M
                </el-tag>
                <el-tag
                  v-if="currentAmounts.length === 0"
                  type="info"
                  size="large"
                  style="margin: 4px 8px 4px 0;"
                >
                  No quick amounts configured
                </el-tag>
              </div>
            </div>

            <!-- 添加新金额 -->
            <div class="add-amount-section">
              <h4>Add New Amount:</h4>
              <el-form
                ref="amountFormRef"
                :model="amountForm"
                :rules="amountRules"
                :inline="true"
              >
                <el-form-item prop="newAmount">
                  <el-input-number
                    v-model="amountForm.newAmount"
                    :min="1"
                    :max="100000"
                    :precision="0"
                    placeholder="Enter amount"
                    size="large"
                    style="width: 200px;"
                    controls-position="right"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    size="large"
                    @click="addAmount"
                    :disabled="!amountForm.newAmount || amountForm.newAmount <= 0"
                  >
                    <el-icon><Plus /></el-icon>
                    Add
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 批量添加常用金额 -->
            <div class="batch-add-section">
              <h4>Quick Add Common Amounts:</h4>
              <div class="preset-amounts">
                <el-button
                  v-for="preset in presetAmounts"
                  :key="`preset-${preset}`"
                  size="small"
                  @click="addPresetAmount(preset)"
                  :disabled="currentAmounts.includes(preset)"
                >
                  {{ preset }}M
                </el-button>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button
                type="primary"
                size="large"
                @click="saveAmounts"
                :loading="isSaving"
                :disabled="currentAmounts.length === 0"
              >
                <el-icon><Check /></el-icon>
                Save Configuration
              </el-button>
              <el-button
                size="large"
                @click="resetToDefault"
                :disabled="isSaving"
              >
                <el-icon><RefreshRight /></el-icon>
                Reset to Default
              </el-button>
              <el-button
                size="large"
                @click="loadAmounts"
                :loading="isLoading"
              >
                <el-icon><Refresh /></el-icon>
                Reload
              </el-button>
            </div>
          </el-card>
        </el-col>

        <!-- Preview and Help Information -->
        <el-col :span="8">
          <!-- Preview Effect -->
          <el-card shadow="hover" style="margin-bottom: 20px;">
            <template #header>
              <div style="display: flex; align-items: center;">
                <el-icon style="margin-right: 8px;"><View /></el-icon>
                <span>Preview Effect</span>
              </div>
            </template>

            <div class="preview-content">
              <h4>User Recharge Page Effect:</h4>
              <div class="preview-amounts">
                <el-button
                  v-for="amount in currentAmounts"
                  :key="`preview-${amount}`"
                  size="small"
                  style="margin: 2px 4px 2px 0;"
                >
                  {{ amount }}
                </el-button>
                <div v-if="currentAmounts.length === 0" style="color: #909399; font-size: 14px;">
                  No quick amount options
                </div>
              </div>
            </div>
          </el-card>

          <!-- Help Information -->
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex; align-items: center;">
                <el-icon style="margin-right: 8px;"><InfoFilled /></el-icon>
                <span>Usage Guide</span>
              </div>
            </template>

            <div class="help-content">
              <h4>Configuration Principles</h4>
              <ul>
                <li>Recommend setting 6-10 different amount options</li>
                <li>Amounts should cover common recharge ranges</li>
                <li>Can set tiered amounts, such as: 100, 500, 1000, 2000, 5000</li>
                <li>Amounts will be automatically deduplicated and sorted in ascending order</li>
              </ul>

              <h4>Usage Tips</h4>
              <ul>
                <li>Click the × on amount tags to delete that amount</li>
                <li>Enter custom amount and click "Add"</li>
                <li>Use "Quick Add" buttons to add common amounts</li>
                <li>Configuration takes effect immediately after saving</li>
              </ul>

              <h4>Important Notes</h4>
              <ul>
                <li>At least one quick amount must be retained</li>
                <li>Amount range: 1 - 100,000M</li>
                <li>Configuration affects all users' recharge pages</li>
                <li>Recommend regular review and optimization</li>
              </ul>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Check, RefreshRight, Refresh, View, InfoFilled } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { trpc } from '../utils/trpc'

// 响应式数据
const amountFormRef = ref<FormInstance>()
const isLoading = ref(false)
const isSaving = ref(false)
const currentAmounts = ref<number[]>([])

// 预设常用金额
const presetAmounts = [50, 100, 200, 500, 1000, 2000, 3000, 5000, 10000, 20000]

// 表单数据
const amountForm = reactive({
  newAmount: null as number | null
})

// 表单验证规则
const amountRules: FormRules = {
  newAmount: [
    { required: true, message: 'Please enter amount', trigger: 'blur' },
    { type: 'number', min: 1, max: 100000, message: 'Amount must be between 1-100000', trigger: 'blur' }
  ]
}

// 方法
const loadAmounts = async () => {
  try {
    isLoading.value = true
    const result = await trpc.admin.getQuickAmounts.query()
    
    if (result.success) {
      currentAmounts.value = result.data.amounts || []
    } else {
      ElMessage.error(result.message || 'Failed to load quick amounts configuration')
    }
  } catch (error: any) {
    console.error('Failed to load quick amounts:', error)
    ElMessage.error('Failed to load quick amounts configuration')
  } finally {
    isLoading.value = false
  }
}

const addAmount = async () => {
  if (!amountFormRef.value) return

  const valid = await amountFormRef.value.validate().catch(() => false)
  if (!valid) return

  const newAmount = amountForm.newAmount!
  
  if (currentAmounts.value.includes(newAmount)) {
    ElMessage.warning('This amount already exists')
    return
  }

  currentAmounts.value.push(newAmount)
  // 去重并排序
  currentAmounts.value = Array.from(new Set(currentAmounts.value)).sort((a, b) => a - b)
  
  // 重置表单
  amountForm.newAmount = null
  amountFormRef.value.resetFields()
  
  ElMessage.success('Amount added successfully')
}

const addPresetAmount = (amount: number) => {
  if (currentAmounts.value.includes(amount)) {
    ElMessage.warning('This amount already exists')
    return
  }

  currentAmounts.value.push(amount)
  // 去重并排序
  currentAmounts.value = Array.from(new Set(currentAmounts.value)).sort((a, b) => a - b)
  
  ElMessage.success(`Added ${amount}M`)
}

const removeAmount = (index: number) => {
  if (currentAmounts.value.length <= 1) {
    ElMessage.warning('At least one quick amount must be retained')
    return
  }

  const removedAmount = currentAmounts.value[index]
  currentAmounts.value.splice(index, 1)
  ElMessage.success(`Removed ${removedAmount}M`)
}

const saveAmounts = async () => {
  if (currentAmounts.value.length === 0) {
    ElMessage.warning('At least one quick amount must be configured')
    return
  }

  // 确认保存
  const confirmed = await ElMessageBox.confirm(
    `Confirm to save quick amount configuration? Total ${currentAmounts.value.length} amount options: [${currentAmounts.value.join(', ')}]M`,
    'Confirm Save',
    {
      confirmButtonText: 'Confirm Save',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).catch(() => false)

  if (!confirmed) return

  try {
    isSaving.value = true
    const result = await trpc.admin.updateQuickAmounts.mutate({
      amounts: currentAmounts.value
    })

    if (result.success) {
      ElMessage.success('Quick amount configuration saved successfully!')
      currentAmounts.value = result.data.amounts
    } else {
      ElMessage.error(result.message || 'Failed to save quick amount configuration')
    }
  } catch (error: any) {
    console.error('Failed to save quick amounts:', error)
    ElMessage.error('Failed to save quick amount configuration')
  } finally {
    isSaving.value = false
  }
}

const resetToDefault = async () => {
  const confirmed = await ElMessageBox.confirm(
    'Confirm to reset to default quick amount configuration? This will overwrite the current configuration.',
    'Confirm Reset to Default',
    {
      confirmButtonText: 'Confirm Reset',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).catch(() => false)

  if (!confirmed) return

  currentAmounts.value = [100, 500, 1000, 2000, 5000, 10000]
  ElMessage.success('Reset to default configuration')
}

// 生命周期
onMounted(() => {
  loadAmounts()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.main-content {
  margin-top: 0;
}

.amounts-list {
  margin-bottom: 30px;
}

.amounts-list h4,
.add-amount-section h4,
.batch-add-section h4,
.preview-content h4,
.help-content h4 {
  margin: 16px 0 12px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.amount-tags {
  min-height: 40px;
  padding: 8px 0;
}

.add-amount-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.batch-add-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9ff;
  border-radius: 8px;
  border: 1px solid #e8eaff;
}

.preset-amounts {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.action-buttons {
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 12px;
}

.preview-content {
  padding: 10px 0;
}

.preview-amounts {
  min-height: 40px;
  padding: 8px 0;
}

.help-content ul {
  margin: 0 0 16px 0;
  padding-left: 18px;
}

.help-content li {
  margin-bottom: 4px;
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style>